package leetcode_1_200;

import java.util.HashMap;
import java.util.Map;

public class LeeCode_166 {
    public static void main(String[] args) {
//        System.out.println(fractionToDecimal(10, 3));
//        System.out.println(fractionToDecimal(1, 3));
//        System.out.println(fractionToDecimal(1, 2));
//        System.out.println(fractionToDecimal(4, 333));
//        System.out.println(fractionToDecimal(1, -3));
//        System.out.println(fractionToDecimal(-22, -2));
        System.out.println(fractionToDecimal(-1, -2147483648));
    }

    private static String fractionToDecimal(int nn, int dd) {
        long d = dd;
        long n = nn;
        Map<Long, Long> map = new HashMap<>();
        StringBuilder sb = new StringBuilder();
        if (n == 0){
            return "0";
        }
        if (d * n < 0){
            sb.append('-');
        }
        d = d < 0 ? -d : d;
        n = n < 0 ? -n : n;
        boolean flag = true;
        if (n < d)
            sb.append(0);
        while (n != 0) {
            while (n < d) {
                n *= 10;
                if (flag) {
                    sb.append('.');
                    flag = false;
                }
                if (n < d) {
                    if (map.containsKey(n)) {
                        long m = map.get(n);
                        String pre = sb.substring(0, (int) m);
                        String aft = sb.substring((int) m, sb.length());
                        return pre + "(" + aft + ")";
                    }
                    sb.append(0);
                    map.put(n, (long) (sb.length() - 1));
                }
            }
            if (map.containsKey(n)) {
                long m = map.get(n);
                String pre = sb.substring(0, (int) m);
                String aft = sb.substring((int) m, sb.length());
                return pre + "(" + aft + ")";
            }
            sb.append(n / d);
            if (!flag)
                map.put(n, (long) (sb.length() - 1));
            n = n % d;
        }
        return sb.toString();
    }
}
